package cn.kai.pet.Consumer;

import cn.kai.basic.config.BussinessException;
import cn.kai.order.domain.OrderPetAcquisition;
import cn.kai.order.service.IOrderPetAcquisitionService;
import cn.kai.order.service.impl.OrderPetAcquisitionServiceImpl;
import cn.kai.pet.domain.SearchMasterMsg;
import cn.kai.pet.mapper.SearchMasterMsgMapper;
import cn.kai.pet.service.ISearchMasterMsgService;
import cn.kai.pet.service.impl.SearchMasterMsgServiceImpl;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;
@Component
public class Consumer {
    //main方法里使用@Autowired注解报空指针错误【记录】  --(CSDN中文章提供的解决方法)
//    @Autowired
//    private IOrderPetAcquisitionService orderPetAcquisitionService;
//    @Autowired
//    private ISearchMasterMsgService searchMasterMsgService;
//    public OrderPetAcquisition methodA(Long id){
//        System.out.println("我进到方法A中了");
//        OrderPetAcquisition order = orderPetAcquisitionService.findById(39L); // 这里也会报空指针
//        System.out.println("取出对象"+order);
//        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionService.findById(id);
//        System.out.println("我执行了A中的方法");
//        return orderPetAcquisition;
//    }
//    public SearchMasterMsg methodB(Long id){
//        SearchMasterMsg searchMasterMsg = searchMasterMsgService.findById(id);
//        return searchMasterMsg;
//    }
//    public void methodC(SearchMasterMsg searchMasterMsg){
//        searchMasterMsgService.update(searchMasterMsg);
//    }
//    public void test(){
//        System.out.println("我进来了");
//    }

    private static OrderPetAcquisitionServiceImpl order = SpringContextUtil.getBean(OrderPetAcquisitionServiceImpl.class);
    private static SearchMasterMsgServiceImpl search = SpringContextUtil.getBean(SearchMasterMsgServiceImpl.class);

    public static void main(String[] args) throws Exception {
        //创建消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("producer_pethome_group");
        //连接MQ
        consumer.setNamesrvAddr("127.0.0.1:9876");
        //消费者订阅主题
        consumer.subscribe("pethome_topic", "pethome_tags");
        //注册监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext conrtext) {
                try {
                    String orderId = null;
                    for (MessageExt msg : msgs) {
                        orderId = new String(msg.getBody(), StandardCharsets.UTF_8);
                    }
                    System.out.println(orderId);
                    Long id = Long.parseLong(orderId);

                    // 使用这种方法解决无法使用@Autowired依赖注入问题
//                    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//                    OrderPetAcquisitionServiceImpl order = context.getBean("orderPetAcquisition",OrderPetAcquisitionServiceImpl.class);
//                    OrderPetAcquisition orderPetAcquisition = order.findById(id); // 这里order是null，报空指针了
                    OrderPetAcquisition orderPetAcquisition = order.findById(id);
                    if (orderPetAcquisition == null){
                        throw new BussinessException("查无此单");
                    }
                    // 订单-1取消 0待处理 1已完成
                    if(orderPetAcquisition.getState() != 1){
                        //如果30s内没有完成订单，则取消订单，放回宠物池，并设置shopId=null
                        //1.根据msgId去查找寻主信息
                        Long msgId = orderPetAcquisition.getSearchMasterMsgId();
//                        SearchMasterMsgServiceImpl search = context.getBean("searchMasterMsg", SearchMasterMsgServiceImpl.class);
                        SearchMasterMsg searchMasterMsg = search.findById(msgId);
                        //2.判断是否有此条寻主讯息
                        if (searchMasterMsg == null){
                            throw new BussinessException("寻主消息不存在，请重新操作");
                        }
                        //3.设置寻主消息的shopId为null，把宠物信息放回宠物池
                        searchMasterMsg.setShopId(null);
                        search.update(searchMasterMsg);
                        //@todo 记录取消日志
                        System.out.println("订单完成超时，已取消订单！");
                    }
                    System.out.println("恭喜您，订单已完成！");


                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }catch (Exception e){
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });
        //启动消费者实例
        consumer.start();
        System.out.printf("Consumer Started.%n");
    }

    /**
     * 在Java中，针对static静态成员，我们有一些最基本的常识：静态变量（成员）它是属于类的，而非属于实例对象的属性；
     * 同样的静态方法也是属于类的，普通方法（实例方法）才属于对象。
     * 而Spring容器管理的都是实例对象，包括它的@Autowired依赖注入的均是容器内的对象实例，
     * 所以对于static成员是不能直接使用@Autowired注入的。
     * @param id
     */

}
